//
//  BLCommonSheet.m
//  Byelone
//
//  Created by 乔小乔 on 2021/2/16.
//

#import "BLCommonSheet.h"
@interface BLCommonSheet()
@property (nonatomic, strong) NSArray *arrayItems;
@end
@implementation BLCommonSheet
{
    void (^blockSelect)(NSInteger index);
}
- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    self.frame = CGRectMake(0, 0, BL_WINDOW_WIDTH, BL_WINDOW_HEIGHT);
    self.viewTop.layer.cornerRadius = 5;
    self.viewTop.layer.masksToBounds = YES;
    self.viewBottom.layer.cornerRadius = 5;
    self.viewBottom.layer.masksToBounds = YES;
}
- (void)showWith:(NSArray *)array block:(void(^)(NSInteger index))over{
    self.arrayItems = array;
    [self createItem];
    if (blockSelect!=over) {
        blockSelect = over;
    }
    UIWindow *window = [[UIApplication sharedApplication]keyWindow];
    [window addSubview:self];
}
- (void)createItem{
    [self.viewTop.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    for (int i=0; i<self.arrayItems.count; i++) {
        NSString *title = self.arrayItems[i];

        UIView *viewLine = [[UIView alloc]initWithFrame:CGRectMake(10, 42*i, BL_WINDOW_WIDTH-20, 1)];
        viewLine.backgroundColor = [UIColor chColorWithHexString:@"F6F6F6"];
        [self.viewTop addSubview:viewLine];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 42*i, BL_WINDOW_WIDTH, 42);
        [btn setTitleColor:[UIColor chColorWithHexString:@"#555555"] forState:UIControlStateNormal];
        [btn setTitle:title forState:UIControlStateNormal];
        btn.tag = i+100;
        [btn addTarget:self action:@selector(clickItem:) forControlEvents:UIControlEventTouchUpInside];
        [self.viewTop addSubview:btn];
    }
    self.layoutHeight.constant = 42*self.arrayItems.count;
}
- (void)clickItem:(UIButton *)sender{
    if (blockSelect) {
        blockSelect(sender.tag-100);
    }
    [self removeFromSuperview];
}
- (IBAction)clickCancel:(id)sender {
    [self removeFromSuperview];
}



+ (void)show:(NSArray *)array click:(void(^)(NSInteger index))over{
    BLCommonSheet *sheet = [[[NSBundle mainBundle]loadNibNamed:@"BLCommonSheet" owner:nil options:nil]lastObject];
    
    [sheet showWith:array block:over];
}
@end
